//
//  BKIntegralViewController.m
//  bestkeep
//
//  Created by yons on 16/12/5.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKIntegralViewController.h"
#import "BKIntegralBookViewController.h"
#import "BKintegralModel.h"
#import "BKMainCommon.h"
#import "BKIntegralHeaderView.h"
#import "BKSignGoodsNameViewCell.h"
#import "BKSignGoodsCollectionViewCell.h"
#import "BKSignVoucherNameViewCell.h"
#import "BKSignVoucherCollectionViewCell.h"
#import "Mediator+BKMy.h"
#import "BKExchangeGoodsViewController.h"
#import "BKExchangeVoucherViewController.h"
#import "BKCollectionViewFlowLayout.h"
#import "BKintegralModel.h"
#import "BKIntegralAllVoucherController.h"
#import "BKIntegralCollectionModel.h"
#import "MJExtension.h"

#define HEIGHT_BKSignHeaderCell  ScreenWidth*430.0/750.0+ScreenWidth*243/1125.0
@interface BKIntegralViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,BKCollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) BKintegralModel *model;//Model
@property(nonatomic,strong) BKIntegralHeaderView *view_tableV_header;
@property(nonatomic,strong) UICollectionReusableView *headerReusableView;
@property(nonatomic,strong) UICollectionReusableView *header_section_one;
@property(nonatomic,strong) ExceptionView *exceptionView;
@property(nonatomic,assign) BOOL isFirst;//第一次加载数据（使用购物车动画）   以后用菊花
@property(nonatomic,strong) NSMutableArray * marr_Cell;

@end

@implementation BKIntegralViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setProperty];
    [self setNav];
    [self createUI];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self check_NetWork];
}
#pragma mark==================setProperty======================
-(void)setProperty{
    
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }

    self.title = @"积分商城";
    self.isFirst = YES;
    
}
#pragma mark ====================设置导航栏========================
-(void)setNav{
    
    
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 28, 28);
    [rightBtn addTarget:self action:@selector(action_rightBtn) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"BKIntegral_wenhaoicon-"] forState:UIControlStateNormal];
    UIBarButtonItem *rewardItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width = -ApplicationNavigationBarBackGauge;
    self.navigationItem.rightBarButtonItems = @[spaceItem,rewardItem];
    
    
    
}

#pragma mark==================createUI======================
-(void)createUI{

    [self.view addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.right.bottom.left.mas_equalTo(self.view);
    }];
}

#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self BK_getData_Integral_FromNetWork];
        }
            break;
        default: {
            [HUD dismiss];

            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
            
        }
            break;
    }
}

#pragma mark--------数据请求----------
-(void)BK_getData_Integral_FromNetWork{
    
    IF(self.isFirst, [LoadingView loadingShoppingCartInView:self.view];, [BKIndicationView showInView:self.view])
    
    [BKIntegralCommon getUserCheckInfo:^(BOOL isSucess, id obj, NSError *error) {
        [LoadingView dismiss];
        [BKIndicationView dismiss];
        if (isSucess) {
            self.isFirst = NO;
            NSDictionary * dic =obj;
            _model =[BKintegralModel mj_objectWithKeyValues:dic];
            [self Create_Marr_Cell];
            [self.view_tableV_header relayOutUI:obj];
            [self.collectionView reloadData];
            
        }else{
            ExceptionCodeType errorType;
            if (error.code == -1009) {
                errorType = ExceptionCodeTypeNoNetwork;
            } else if (error.code == -1001){
                errorType = ExceptionCodeTypeRequestFailed;
            }else if(error.code == 502 || error.code == 404){
                errorType =  ExceptionCodeTypeServerError;
            } else {
                errorType = ExceptionCodeTypeFailedToLoad;
            }
            self.exceptionView = [ExceptionView exceptionViewWithType:errorType];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self BK_getData_Integral_FromNetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
        if (error) {
            
            ExceptionCodeType errorType;
            if (error.code == -1009) {
                errorType = ExceptionCodeTypeNoNetwork;
            } else if (error.code == -1001){
                errorType = ExceptionCodeTypeRequestFailed;
            }else if(error.code == 502 || error.code == 404){
                errorType =  ExceptionCodeTypeServerError;
            } else {
                errorType = ExceptionCodeTypeFailedToLoad;
            }
            self.exceptionView = [ExceptionView exceptionViewWithType:errorType];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self BK_getData_Integral_FromNetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
    }];
}


-(void)action_rightBtn{
    BKIntegralBookViewController *integralBookVC = [[BKIntegralBookViewController alloc]init];
    integralBookVC.urlString = @"http://cdn.bestkeep.cn/ui/mobile/html/Integral.html";
    [self.navigationController pushViewController:integralBookVC animated:YES];
    integralBookVC.view.backgroundColor = ThemeBackgroundColor;
}

#pragma mark - <UICollectionViewDataSource>
// 设置headerView和footerView的
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        BKIntegralCollectionModel * model=self.marr_Cell[indexPath.section];
        if (model.isHaveHeader) {
            return [self bk_collectionView:collectionView forIndexPath:indexPath];
        }
    }
    return nil ;
}
-(UICollectionReusableView*)bk_collectionView:(UICollectionView*)collectionView forIndexPath:(NSIndexPath *)indexPath{
    if (!_header_section_one) {
        _header_section_one= [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
        _header_section_one.backgroundColor=[UIColor clearColor];
        [_header_section_one addSubview:self.view_tableV_header];
    }
    return _header_section_one;
}
// 设置section头视图的参考大小，与tableheaderview类似
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    BKIntegralCollectionModel * model=self.marr_Cell[section];
    return model.header_size;
}
//设置section的颜色
- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout colorForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_Cell[section];
    return model.section_color;
}
//设置item的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    BKIntegralCollectionModel * model=self.marr_Cell[indexPath.section];
    return model.item_size;
}
//设置section的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_Cell[section];
    return model.section_Edge;
}
// 两个cell之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_Cell[section];
    return model.interitemSpacing;
}
// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_Cell[section];
    return model.lineSpacing;
}
//numberOfItemsInSection
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    BKIntegralCollectionModel * model=self.marr_Cell[section];
    if ([model.id_dentifier isEqualToString:@"BKSignVoucherCollectionViewCell"]) {
        return _model.couponList.count>4?4:_model.couponList.count;
    }else if([model.id_dentifier isEqualToString:@"BKSignGoodsCollectionViewCell"]){
        return _model.integralGoodsList.count;
    }else if([model.id_dentifier isEqualToString:@"BKSignGoodsNameViewCell"]){
        return 1;
    }else if([model.id_dentifier isEqualToString:@"BKSignVoucherNameViewCell"]){
        return 1;
    }
    return 0;
}
//numberOfSections
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.marr_Cell.count;
}
//UICollectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell*  cell=nil;
    BKIntegralCollectionModel * model=self.marr_Cell[indexPath.section];
    IF(model.id_dentifier, cell =[collectionView dequeueReusableCellWithReuseIdentifier:model.id_dentifier forIndexPath:indexPath], )
    if ([model.id_dentifier isEqualToString:@"BKSignVoucherCollectionViewCell"]) {
        if (_model.couponList.count>=indexPath.row) {
            [(BKSignVoucherCollectionViewCell*)cell relayOutUI:_model.couponList[indexPath.row]];
        }
    }else if([model.id_dentifier isEqualToString:@"BKSignGoodsCollectionViewCell"]){
        if (_model.integralGoodsList.count>=indexPath.row) {
            [(BKSignGoodsCollectionViewCell*)cell relayOutUIWithModel:_model.integralGoodsList[indexPath.row]];
        }
    }else if([model.id_dentifier isEqualToString:@"BKSignVoucherNameViewCell"]){
        IF(_model.couponList.count<=4, [(BKSignVoucherNameViewCell*)cell MoreHidden], [(BKSignVoucherNameViewCell*)cell MoreShow])
        [(BKSignVoucherNameViewCell*)cell Set_lab_AcTime:_model.endDate];
    }
    return cell;
}
//didSelect
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    BKIntegralCollectionModel * model=self.marr_Cell[indexPath.section];
    if ([model.id_dentifier isEqualToString:@"BKSignVoucherCollectionViewCell"]) {
        BKExchangeVoucherViewController *exchangeVoucher = [[BKExchangeVoucherViewController alloc] init];
        BKSignVoucherModel * model = [_model.couponList objectAtIndex:(indexPath.row)];
        exchangeVoucher.couponId=model.couponId;
        [self.navigationController pushViewController:exchangeVoucher animated:YES];
    }else if([model.id_dentifier isEqualToString:@"BKSignGoodsCollectionViewCell"]){
        BKExchangeGoodsViewController * vc =[[BKExchangeGoodsViewController alloc]init];
        BKSignGoodsModel * model=[_model.integralGoodsList objectAtIndex:(indexPath.row)];
        vc.exchangeId=model.exchangeId;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([model.id_dentifier isEqualToString:@"BKSignGoodsNameViewCell"]){
    }else if([model.id_dentifier isEqualToString:@"BKSignVoucherNameViewCell"]){//查看更多优惠券
        if (_model.couponList.count>4) {
            BKIntegralAllVoucherController * vc =[[BKIntegralAllVoucherController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}
#pragma =======================初始化==============================
/*
 * view_tableV_header
 */
-(BKIntegralHeaderView *)view_tableV_header{
    if (!_view_tableV_header) {
        _view_tableV_header=[[BKIntegralHeaderView alloc]init];
        _view_tableV_header.frame=CGRectMake(0, 0, SCREENWIDTH, HEIGHT_BKSignHeaderCell);
    }
    return _view_tableV_header;
}
/*
 * collectionView
 */
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        
        //创建一个layout布局类
        BKCollectionViewFlowLayout * layout = [[BKCollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView=[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor=RGB(241, 242, 243);
        _collectionView.dataSource=self;
        _collectionView.delegate=self;
        [_collectionView registerClass:NSClassFromString(@"BKSignVoucherNameViewCell") forCellWithReuseIdentifier:@"BKSignVoucherNameViewCell"];
        [_collectionView registerClass:NSClassFromString(@"BKSignVoucherCollectionViewCell") forCellWithReuseIdentifier:@"BKSignVoucherCollectionViewCell"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
        
        [_collectionView registerClass:NSClassFromString(@"BKSignGoodsNameViewCell") forCellWithReuseIdentifier:@"BKSignGoodsNameViewCell"];
        [_collectionView registerClass:NSClassFromString(@"BKSignGoodsCollectionViewCell") forCellWithReuseIdentifier:@"BKSignGoodsCollectionViewCell"];
    }
    return _collectionView;
}

-(void)Create_Marr_Cell{
    _marr_Cell=[[NSMutableArray alloc]init];
    /*
     * 如果后台没有优惠券-》不显示
     */
    if (!_model.couponList||_model.couponList.count==0) {
        
    }else{
        BKIntegralCollectionModel * model0=[[BKIntegralCollectionModel alloc]init];
        model0.header_size=CGSizeMake(SCREENWIDTH, HEIGHT_BKSignHeaderCell+10);
        model0.item_size=CGSizeMake(SCREENWIDTH,44);
        model0.section_color=[UIColor whiteColor];
        model0.section_Edge=UIEdgeInsetsMake(0, 0, 0, 0);
        model0.interitemSpacing=0.1;
        model0.lineSpacing=0.1;
        model0.isHaveHeader=YES;
        model0.id_dentifier=@"BKSignVoucherNameViewCell";
        [_marr_Cell addObject:model0];
        
        BKIntegralCollectionModel * model1=[[BKIntegralCollectionModel alloc]init];
        model1.header_size=CGSizeMake(0, 0);
        model1.item_size=CGSizeMake((SCREENWIDTH-2.0*ApplicationBackGauge)/2.0-5.0f,110+10);
        model1.section_color=[UIColor whiteColor];
        model1.section_Edge=UIEdgeInsetsMake(0, ApplicationBackGauge, 25, ApplicationBackGauge);
        model1.interitemSpacing=0.1;
        model1.lineSpacing=0.1;
        model1.isHaveHeader=NO;
        model1.id_dentifier=@"BKSignVoucherCollectionViewCell";
        [_marr_Cell addObject:model1];
    }
    
    BKIntegralCollectionModel * model2=[[BKIntegralCollectionModel alloc]init];
    model2.item_size=CGSizeMake(SCREENWIDTH,54);
    model2.section_color=[UIColor clearColor];
    model2.section_Edge=UIEdgeInsetsMake(0, 0, 0, 0);
    model2.interitemSpacing=0.1;
    model2.lineSpacing=0.1;
    if (!_model.couponList||_model.couponList.count==0) {
        model2.isHaveHeader=YES;
        model2.header_size=CGSizeMake(SCREENWIDTH, HEIGHT_BKSignHeaderCell+10);
    }else{
        model2.header_size=CGSizeMake(0, 0);
        model2.isHaveHeader=NO;
    }

    model2.id_dentifier=@"BKSignGoodsNameViewCell";
    [_marr_Cell addObject:model2];
    
    BKIntegralCollectionModel * model3=[[BKIntegralCollectionModel alloc]init];
    model3.header_size=CGSizeMake(0, 0);
    model3.item_size=CGSizeMake((SCREENWIDTH-2.0*ApplicationBackGauge)/2.0-5.0f,473/2.0);
    model3.section_color=[UIColor clearColor];
    model3.section_Edge=UIEdgeInsetsMake(0, ApplicationBackGauge, 50, ApplicationBackGauge);
    model3.interitemSpacing=0.1;
    model3.lineSpacing=10;
    model3.isHaveHeader=NO;
    model3.id_dentifier=@"BKSignGoodsCollectionViewCell";
    [_marr_Cell addObject:model3];
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end























